import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/1/4.
 */
public class E19_OrnamentalGarden {
    public static void main(String[] args) throws Exception {
        final int count = 200;
      List<Thread> t = new ArrayList<Thread>();
        //加大线程数，增加执行时间，放大问题
        for (int i = 0; i < count; i++) {
            t.add(new Thread(new Entrance(i)));
            t.get(i).start();
        }
        //Run for a while ,then stop and collect the data
        TimeUnit.SECONDS.sleep(30);
        for (int i = 0; i < count; i++) {
           t.get(i).interrupt();
        }
        System.out.println("Total: " + Entrance.getTotalCount());
        System.out.println("Sum of Entrances: " + Entrance.sumEntrances());
    }
}

class Count {
    private int count = 0;
    private Random rand = new Random(47);

    public synchronized int increment() {
        int temp = count;

        if (rand.nextBoolean()) {
            Thread.yield();
        }
        return (count = ++temp);
    }

    public int value() {
        return count;
    }
}

class Entrance implements Runnable {
    private static Count count = new Count();
    private static List<Entrance> entranceList = new ArrayList<Entrance>();
    private int number = 0;
    private final int id;

    public Entrance(int id) {
        this.id = id;
        entranceList.add(this);
    }

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                number++;
            }
            //我放大了并发，由于控制台输出是原子性，我注释掉这个输出。减少影响
            //System.out.println(this + " Total:" + count.increment());
            count.increment();
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("sleep interrupte and Stoping "+this);
                return;
            }
        }
    }

    @Override
    public String toString() {
        return "Entrance " + id + ":" + getValue();
    }

    public static int getTotalCount() {
        return count.value();
    }

    public static int sumEntrances() {
        int sum = 0;
        for (Entrance entrance : entranceList) {
            sum += entrance.getValue();
        }
        return sum;
    }
    public synchronized int getValue() {
        return number;
    }
}